/**
 * SignTool.java 
 * Copyright © 2015-3015, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2014年9月24日
 */
package com.pshare.wx.tool;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.apache.commons.lang3.StringUtils;

import com.tenpay.util.MD5Util;
import com.tenpay.util.Sha1Util;

/**
 * 
 */
public class SignTool {
	
	/**
	 * 订单数据打包，携带一个md5签名
	 * @param parameters
	 * @param partnerKey
	 * @return String
	 * @throws UnsupportedEncodingException
	 */
	public static String getRequestURL(SortedMap<String, String> parameters, String partnerKey) throws UnsupportedEncodingException {
		String sign = createSign(parameters, partnerKey);
		
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			sb.append(k + "=" + URLEncoder.encode(v, "UTF-8") + "&");
		}
		
		return sb.append("sign=" + sign).toString();
	}

	
	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 * @param params
	 * @param keyValue
	 * @return String
	 */
	protected static String createSign(SortedMap<String, String> parameters, String partnerKey) {
		StringBuffer sb = new StringBuffer();
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			if(StringUtils.isNotBlank(v)  
					&& !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + partnerKey);
		
		return MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
	}
	
	/**
	 * 创建app_signature签名，使用SHA1签名算法
	 * @param params
	 * @return String
	 */
	public static String genSign(SortedMap<String, String> params) {
		StringBuffer sb = new StringBuffer();
		Set es = params.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + v + "&");
		}
		String paramsStr = sb.substring(0, sb.lastIndexOf("&"));
		return Sha1Util.getSha1(paramsStr);
	}
	
}
